package com.lanou.musicbox.fragment.seekmusic;


import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lanou.musicbox.R;
import com.lanou.musicbox.adapter.seekmusic.SearchingActivityGirdViewAdapter;
import com.lanou.musicbox.adapter.seekmusic.SeekMusicAdapter;
import com.lanou.musicbox.bean.SearchSongEntity;
import com.lanou.musicbox.bean.SeekMusic;
import com.lanou.musicbox.bean.SongSearch;
import com.lanou.musicbox.utils.Contant;
import com.lanou.musicbox.utils.VolleySingleton;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 赵宝龙 on 15/10/20.
 * 搜索界面
 */
public class SeekMusicsFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener {

    private EditText seekeditText;
    private ImageView startSeek;
    private GridView seekmusicGridView;
    private ListView seekmusicListView;
    private RequestQueue requestQueue;
    private List<SeekMusic.DataEntity> data;
    private SearchingActivityGirdViewAdapter adapter;
    private EnterTheSeekMusicFragment fragment;
    private LinearLayout grid_liner;
    private ArrayList<SearchSongEntity> entity;
    private SeekMusicAdapter searchAdapter;
    private Handler mHandler;
    private FragmentManager manager;// 管理fragment跳转
    private InputMethodManager imm;
    private View view;



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.seekmusic, null);// 绑定布局
        seekeditText = (EditText) view.findViewById(R.id.seekeditText);// 初始化
        startSeek = (ImageView) view.findViewById(R.id.startSeek);
        seekmusicGridView = (GridView) view.findViewById(R.id.seekmusicGridView);
        seekmusicGridView.setCacheColorHint(1);// 将GridView设为透明
        grid_liner = (LinearLayout) view.findViewById(R.id.grid_liner);
        seekmusicListView = (ListView) view.findViewById(R.id.seekmusicListView);
        seekmusicListView.setCacheColorHint(1);// 将ListView设为透明

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mHandler = new Handler();// 线程初识化
        startSeek.setOnClickListener(this);// 设置监听
        seekmusicGridView.setOnItemClickListener(this);
        requestQueue = VolleySingleton.getInstance(getActivity()).getRequestQueue();
        seekmusicListView.setOnItemClickListener(this);
        adapter = new SearchingActivityGirdViewAdapter(getActivity());// 初始化adapter
        getInternetData(); // 从网络上拉取热门搜索的数据的方法
        manager = getActivity().getSupportFragmentManager();




    }

    @Override
    public void onResume() {
        super.onResume();
        seekeditText.setText("");// 设置为string类型
        TextChanged();// 定义文本改变的方法
    }

    //文本改变方法
    public void TextChanged() {
        seekeditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    seekmusicListView.setVisibility(View.GONE);
                    grid_liner.setVisibility(View.VISIBLE);
                } else {
                    grid_liner.setVisibility(View.GONE);
                    seekmusicListView.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

                // 加入队列
                mHandler.post(runnable);

            }
        });
    }

    //利用线程实现界面更新
    Runnable runnable = new Runnable() {
        String url;

        @Override
        public void run() {
            //获取数据
            final String datas = seekeditText.getText().toString();
            //转为utf_8
            try {
                String songUrl = URLEncoder.encode(datas, "UTF-8");
                //网址拼接
                url = Contant.Url.URL_Seek_songs_link + songUrl;
                //网络请求
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            StringRequest request = new StringRequest(url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Gson gson = new Gson();
                    SongSearch songSearch = gson.fromJson(response, SongSearch.class);
                    //获取数据
                    entity = songSearch.getSong();
                    searchAdapter = new SeekMusicAdapter(getActivity(), entity);
                    seekmusicListView.setAdapter(searchAdapter);// 绑定adapter

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
            requestQueue.add(request);
        }
    };


    //从网络上拉取热门搜索的数据
    private void getInternetData() {
        String url = Contant.Url.URL_Seek_hot_songs;
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Gson gson = new Gson();
                SeekMusic entity = gson.fromJson(s, SeekMusic.class);
                if (entity != null && entity.getData() != null) {
                    data = entity.getData();
                    adapter.setDatas(data);
                    seekmusicGridView.setAdapter(adapter);
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        requestQueue.add(request);
    }

    @Override
    public void onClick(View v) {// 监听方法
        switch (v.getId()) {
            case R.id.startSeek:// 点击搜索图片
                String songName = seekeditText.getText().toString();// 转换成string类型

                if (songName.trim().length() <= 0) {
                    Toast.makeText(getActivity(), "请输入相关内容", Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        String str = URLEncoder.encode(songName, "UTF-8");
                        Bundle bundle = new Bundle();
                        bundle.putString("url", str);
                        fragment = new EnterTheSeekMusicFragment();
                        fragment.setArguments(bundle);
                        manager
                                .beginTransaction()
                                .replace(R.id.fill_main, fragment)
                                .addToBackStack(null)
                                .commit();
                        //设置键盘跳转后自动消失
                        InputMethodManager imm = (InputMethodManager)getActivity()
                                .getSystemService(Context.INPUT_METHOD_SERVICE);
                        //imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                        if (imm.isActive()){
                            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                        }

                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }

                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // Log.i("ZBL", "点了了");
        switch (parent.getId()) {
            case R.id.seekmusicGridView:// 点击GridView时

                TextView text = (TextView) view.findViewById(R.id.search_grid_text);
                String string = text.getText().toString();
                try {

                    String str = URLEncoder.encode(string, "UTF-8");
                    Bundle bundle = new Bundle();
                    bundle.putString("url", str);
                    fragment = new EnterTheSeekMusicFragment();
                    fragment.setArguments(bundle);
                    manager
                            .beginTransaction()
                            .addToBackStack(null)
                            .replace(R.id.fill_main, fragment)
                            .commit();
                    //设置键盘跳转后自动消失
                    InputMethodManager imm = (InputMethodManager)getActivity()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()){
                        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                    }
                    //imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.seekmusicListView:// 点击ListView时
                TextView list_text = (TextView) view.findViewById(R.id.search_list_text);
                String stringOne = list_text.getText().toString();
                try {

                    String strOne = URLEncoder.encode(stringOne, "UTF-8");
                    Bundle bundle = new Bundle();
                    bundle.putString("url", strOne);
                    fragment = new EnterTheSeekMusicFragment();
                    fragment.setArguments(bundle);
                    manager
                            .beginTransaction()
                            .addToBackStack(null)
                            .replace(R.id.fill_main, fragment)
                            .commit();
                    //设置键盘跳转后自动消失
                    InputMethodManager imm = (InputMethodManager)getActivity()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()){
                        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                    }
                   // imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
